package com.android.manghe.mine.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.DisplayUtil
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.common.activity.PayFailActivity
import com.android.manghe.common.activity.PaySuccessActivity
import com.android.manghe.common.model.BuyGoodShangMengZhiFuRes
import com.android.manghe.common.model.PaymentTypeRes
import com.android.manghe.common.webview.SimpleWebViewActivity
import com.android.manghe.config.events.RefreshMemberInfoEvent
import com.android.manghe.config.events.RefreshOrdersEvent
import com.android.manghe.coupon.adapter.PaymentAdapter
import com.android.manghe.mine.model.MyOrderDetailRes
import com.android.manghe.mine.presenter.PMarketOrderDetail
import com.android.manghe.quickpay.activity.QuickPayDetailActivity
import com.android.manghe.user.activity.LoginActivity
import com.android.manghe.view.AutoHeightLayoutManager
import com.android.manghe.view.dialog.ConfirmPayResultDialog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_market_order_detail.*
import java.math.BigDecimal

/**
 * 商城订单详情（二次支付）
 * @author ZhangWeiJun
 * @date 2019/6/14
 */

class MarketOrderDetailActivity : MVPActivity<PMarketOrderDetail>() {
    companion object {
        fun showActivity(context: Context, orderSN: String) {
            val intent = Intent(context, MarketOrderDetailActivity::class.java)
            intent.putExtra("orderSN", orderSN)
            context.startActivity(intent)
        }
    }

    private var mPaymentAdapter: PaymentAdapter? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_market_order_detail
    }

    override fun initData(savedInstanceState: Bundle?) {
        titleBar.setToolbar("订单详情").setLeftIcon(R.mipmap.icon_back_black)
            .setTitleAndStatusBgColor(R.color.white)
        p.orderSN = intent.getStringExtra("orderSN")

        if (UserHolder.getUserInfo(this) == null) {
            finish()
            open(LoginActivity::class.java)
            return
        }


        tvOrderSN.text = p.orderSN

        paymentRecyclerView.layoutManager =
            AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mPaymentAdapter = PaymentAdapter(this, ArrayList<PaymentTypeRes.DataBean.PaymentBean>())
        mPaymentAdapter!!.hideDesc()
        paymentRecyclerView.addItemDecoration(
            RecyclerViewDivider(
                this,
                LinearLayoutManager.HORIZONTAL
            )
        )
        paymentRecyclerView.adapter = mPaymentAdapter
        mPaymentAdapter?.setOnItemClickListener { adapter, _, position ->
            val item = adapter.data[position] as PaymentTypeRes.DataBean.PaymentBean
            mPaymentAdapter?.selectedItem(item)
            p.setPayType(item)
        }


        p.getOrderDetail()
        p.getPaymentType()
        btn.setOnClickListener {
            when (p.orderDetail.status_id) {
                100 -> {
                    //支付
                    p.toPay()
                }
                102 -> {
                    //确认收货
                    AlertDialog.Builder(this)
                        .setTitle("是否确认收到货物？")
                        .setPositiveButton(
                            "确定"
                        ) { _, _ ->
                            p.confirmOrder()
                        }
                        .setNegativeButton("取消") { dialog, _ ->
                            dialog.dismiss()
                        }
                        .create().show()
                }
                110 -> {
                    //已收货
                    if (TextUtils.equals("0", p.orderDetail.is_rate)) {
                        //晒单
                        MarketShowOrderActivity.showActivity(
                            this,
                            p.orderDetail.id,
                            p.orderDetail.goods[0].good_id,
                            p.orderDetail.goods[0].img_src,
                            p.orderDetail.goods[0].goods_name
                        )
                    }
                }
            }
        }
        Bus.observe<RefreshOrdersEvent>().subscribe {
            p.getOrderDetail()
        }.registerInBus(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun update(data: MyOrderDetailRes.DataBean) {
        //地址
        tvAddrName.text = data.name
        tvAddrTel.text = data.mobile
        tvAddrDetail.text = data.area + " " + data.address

        //商品信息
        rvGood.layoutManager = AutoHeightLayoutManager(this)
        val adapter = GoodListAdapter(this, data.goods)
        rvGood.adapter = adapter

        tvStatus.text = data.status_name

        //金额
        tvResultPay.text = "￥${data.order_amount}"
        var totalPrice = 0.00
        data.goods.forEach {
            totalPrice += it.sell_price.toFloat() * it.buy_num.toInt()
        }
        val bigDecimal = BigDecimal(totalPrice)
        totalPrice = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toDouble()
        tvPrice.text = totalPrice.toString()

        //物流信息
        tvLogistics.text = data.express_name
        tvRemark.text = data.order_tip

        btn.visibility = View.VISIBLE
        //按钮
        when (data.status_id) {
            100 -> {
                //待支付
                btn.text = "立即支付"
                layoutPayment.visibility = View.VISIBLE
            }
            101 -> {
                //待发货
                btn.visibility = View.GONE
            }
            102 -> {
                //已发货
                btn.text = "确认收货"
            }
            110 -> {
                //已收货
                if (TextUtils.equals("1", data.is_rate)) {
                    //已晒单
                    btn.visibility = View.GONE
                } else {
                    //已完成 未晒单
                    btn.text = "立即评价"
                }
            }
            111 -> {
                tvStatus.text = "已取消"
            }
        }
    }


    fun updatePayments(paymentList: List<PaymentTypeRes.DataBean.PaymentBean>) {
        mPaymentAdapter?.let {
            it.update(paymentList)
        }
        try {
            val lp = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                paymentList.size * DisplayUtil.dip2px(this, 60f)
            )
            lp.topMargin = DisplayUtil.dip2px(this, 20f)
            lp.bottomMargin = DisplayUtil.dip2px(this, 20f)
            paymentRecyclerView.layoutParams = lp
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }


    fun payFail() {
        ToastUtil.showShort(this, "未完成支付")
    }

    fun paySuccess() {
        finish()
        open(PaySuccessActivity::class.java)
    }

    fun toPayByH5(url: String) {
        SimpleWebViewActivity.showActivity(this, url, "支付")
    }

    fun toPayByBrowser(url: String, orderId: String) {
        val uri: Uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
        //弹出让用户确定是否支付成功的弹出框
        orderId?.let {
            val dialog =
                ConfirmPayResultDialog(this, orderId, object : ConfirmPayResultDialog.CallBack {
                    override fun callBack(orderId: String) {
                        //显示支付成功界面
                        p.checkOrderStatus(orderId)
                    }
                })
            dialog.show()
        }
    }


    class GoodListAdapter(context: Context, data: List<MyOrderDetailRes.DataBean.GoodsBean>) :
        BaseQuickAdapter<MyOrderDetailRes.DataBean.GoodsBean, BaseViewHolder>(R.layout.item_order_detail_good, data) {
        var context: Context? = null

        init {
            this.context = context
        }

        override fun convert(
            helper: BaseViewHolder,
            item: MyOrderDetailRes.DataBean.GoodsBean
        ) {
            GlideHelper.loadRoundTrans(context, item.img_src, helper.getView(R.id.ivPic), 6)
            helper.setText(R.id.tvTitle, item.goods_name)
            helper.setText(R.id.tvAmount, "x${item.buy_num}")
            helper.setText(R.id.tvSellPrice, "￥${item.sell_price}")

        }

    }

    fun openQuickPay(buyGoodShangMengZhiFuData: BuyGoodShangMengZhiFuRes.DataBean){
        open(QuickPayDetailActivity::class.java, mapOf("buyGoodShangMengZhiFuData" to buyGoodShangMengZhiFuData, "secondPay" to true), 2000)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == 1000 || requestCode == 2000){
                if(data != null  && data.extras != null && data.extras.getBoolean("fail" , false)){
                    finish()
                    open(PayFailActivity::class.java)
                    Bus.send(RefreshMemberInfoEvent())
                    return
                }
                //翼支付支付结束，查询支付结果
                finish()
                open(PaySuccessActivity::class.java)
            }
        }
    }
}